<?php
/**
 * 创客发工资服务类
 * @author liujun
 */
namespace App\System\Cis\Services;

use App\Jobs\SendMsg;
use App\System\Base\Repositories\BaseHolidayRepository;
use App\System\Base\Repositories\BaseSettingRepository;
use App\System\Cis\Repositories\CisUserRepository;
use App\System\Fina\Repositories\FinaIntegralRegRecordRepository;
use Illuminate\Support\Facades\DB;

class DailyWagePlanningTaskService
{
    /**
     * 错误信息
     * @var
     */
    private $errorMsg;

    /**
     * 用户模型对像
     * @var
     */
    private $userObj;

    /**
     * 可发工资的用户数组
     * @var array
     */
    private $paycheckUser = [];

    /**
     * 工资设置信息
     * @var
     */
    private $setting = [];

    /**
     * @var
     * 短信内容数组
     */
    private $smsData;

    public function __construct()
    {
        $this->userObj = CisUserRepository::getInstance();
    }

    /**
     * 发日工资总入口（待结算的）
     */
    public function dailyWage()
    {
        $this->updateRecommendedNumber();
        $holiday = BaseHolidayRepository::getInstance();
        $res = $holiday->getOne(date("Y-m-d"));//查询当天是否后台设置的节假日
        if($res)
        {//是不于发放
            return '后台设置，非发放工资日期';
        }
        if(date("N") > 5)
        {//周六日不发放工资
            return '周未，非发放工资日期';
        }
        DB::beginTransaction();
        $this->getUserList();//获取可发工次的用户
        if($this->errorMsg) return $this->errorMsg;
        $this->getSetting();//获取配置信息
        $this->pay();//支付工资
        if($this->errorMsg) return $this->errorMsg;
        DB::commit();
        //DB::rollBack();
    }

    /**
     * 结算日工资总入口
     */
    public function settlementDayWages()
    {
        DB::beginTransaction();
        $this->updateFinance();//更新用户钱包
        if ($this->errorMsg) return $this->errorMsg;
        DB::commit();
        //$this->sendMsg();//异步通知发送短信
    }

    /**
     * 获取可发工资的用户
     */
    private function getUserList()
    {
       $user_list =  $this->userObj->getPaycheckUser();
       if(!$user_list)
       {
            return $this->errorMsg = '没有可发工次的创客';
       }
       return $this->paycheckUser = $user_list;
    }

    /**
     * 获取设置信息,并组装格式
     * @return mixed
     */
    private function getSetting()
    {
        $setting_array = [];
        $setting = BaseSettingRepository::getInstance()->getSetting();
        $array_key = [1=>'y',2=>'x',3=>'d',4=>'g'];//y创业区业绩 x创新区业绩 d懂事区业绩 g日工资
        for ($i=0;$i<13;$i++)
        {
            $level_setting = [];
            if($i == 0)
            {
                $level_setting['y'] = 1000;
                $level_setting['x'] = 1000;
                $level_setting['d'] = 0;
                $level_setting['g'] = 46;
            }
            else
            {

                if($i == 7) continue;

                for ($j=1;$j<5;$j++)
                {
                    $level_setting[$array_key[$j]] = isset($setting[$i.$j]) ? $setting[$i.$j] : 0;
                }
            }
            $setting_array[$i] = $level_setting;
        }
        return $this->setting =$setting_array;
    }

    /**
     * 匹配工资系数
     */
    private function matchedWageCoefficient($user)
    {
        $setting_key = 0;
        foreach ($this->setting as $k => $v)
        {
            if($user['y'] >= $v['y'] && $user['x'] >= $v['x'] && $user['d'] >= $v['d'])
            {
                if($k > $setting_key)
                {//匹配大的就更新
                    $setting_key = $k;
                }
            }
        }

        if($setting_key == 0)
        {//35元档工资
            if(($user['y'] + $user['x']) < 3000)
            {//不满足3000业绩，不发放
                $setting_key = '一';
            }
           /* else
            {
                $res = $this->userObj->findRecommendedNumber($user['id']);//查询是否满足直推三个人的条件
                if($res)
                {*/
                    if(!$user['f'])
                    {//没有复销日期
                        $set = ['repeated_consumption_date'=>date("Y-m-d",strtotime("+29 day")),'user_renew'=>1];
                        $this->userObj->updateUser($set,$user['id']);//复消日期为空则更新复销日期
                    }
               /* }
                else
                {//不满足直推三个人不发放工资
                    $setting_key = '一';
                }

            }*/
        }
        else
        {//35元以上的
            if(!$user['f'])
            {//没有复销日期
                $set = ['repeated_consumption_date'=>date("Y-m-d",strtotime("+29 day")),'user_renew'=>1];
                $this->userObj->updateUser($set,$user['id']);//复消日期为空则更新复销日期
            }
        }
        return $setting_key;
    }

    /**
     * 发工资(循环用户进行发工资操作)
     */
    private function pay()
    {
        foreach ($this->paycheckUser as $v)
        {
            $setting_key = $this->matchedWageCoefficient($v);
            if($setting_key === '一')
            {
                continue;
            }

            $this->generateFinancialRecord($v,$this->setting[$setting_key]['g']);
            if($this->errorMsg)
            {
                return $this->errorMsg;
            }
        }
    }

    /**
     * 生成财务记录，并更新用户钱包冻结金额
     * @param $user 用户信息
     * @param $cash 工资金额
     * @return string
     */
    private function generateFinancialRecord($user,$cash)
    {
        if(!$cash)
        {
            return false;
        }
        $commission = ($cash * 0.1)/2;//积分注册各自手续费
        $cash = $cash/2-$commission;//积分注册币各收入
        $set = [
            'income'=>1,
            'type'=>6,
            'cash'=>$cash,
            'after_cash' => 0,
            'commission'=>$commission,
            'status'=>3,
        ];
        $finaObj = FinaIntegralRegRecordRepository::getInstance();
        for($i=1;$i<3;$i++)
        {
            $set['record_type'] = $i;
            $set['user_id'] = $user['id'];
            $fina_id = $finaObj->createFina($set);//生成服务奖励财务记录
            if(!$fina_id)
            {
                return $this->errorMsg = '工资财务生成失败';
            }
            $res = $this->updateUserWallet($user['id'],$set['cash'],$i+2);
            if(!$res)
            {
                return $this->errorMsg = '更新用户冻结金额出错';
            }
        }
    }

    /**
     * 查询待结算财务
     */
    private function getUnsettledFinance()
    {
        $fina = FinaIntegralRegRecordRepository::getInstance();
        $end_time = date("Y-m-d",strtotime("-1 day"));//上线后去掉注释
        //$end_time = date("Y-m-d");//暂时写死
        $list = $fina->getUnsettledFinance($end_time);
        if(!$list)
        {
            return $this->errorMsg = '未有待结算的财务';
        }
        return $list;
    }

    /**
     * 更新用户钱包
     * @param $user_id 用户ID
     * @param $cash 金额
     * @param $record_type 货币类型 1积分 2注册币 3 冻结的积分 4冻结的注册币
     * @param $income 1增加 2减少
     *
     */
    private function updateUserWallet($user_id,$cash,$record_type,$income=1)
    {
        $column_array = [1=>'integral',2=>'registered_currency',3=>'freeze_integral',4=>'freeze_registered_currency'];
        $res = $this->userObj->updateUserPurse($user_id,$income,$column_array[$record_type],$cash);
        if(!$res)
        {
            return $this->errorMsg = '更新用户钱包出错';
        }
        return $res;
    }

    /**
     * 更新财务，及用户钱包
     * @return string
     */
    private function updateFinance()
    {
        $list = $this->getUnsettledFinance();//查询待结算财务
        if($this->errorMsg) return $this->errorMsg;
        $fina = FinaIntegralRegRecordRepository::getInstance();
        $set = ['status'=>1,'reasons'=>'系统自动发放'];
        foreach ($list as $v)
        {
            $after_cash = 0;
            if($v['record_type'] == 1)
            {
                $after_cash = $v['user']['integral'] + $v['cash'];
            }
            else
            {
                $after_cash = $v['user']['registered_currency'] + $v['cash'];
            }

            //更新财务状态
            $set['after_cash'] = $after_cash;
            $res = $fina->updateFina($set,$v['id']);
            //更新用户钱包
            if(!$res)
            {
                return $this->errorMsg = '更新财务出错';
            }
            $this->updateUserWallet($v['user_id'],$v['cash'],$v['record_type']);//增加可用金额
            if($this->errorMsg) return $this->errorMsg;
            $this->updateUserWallet($v['user_id'],$v['cash'],$v['record_type']+2,2);//减少冻结金额
            if($this->errorMsg) return $this->errorMsg;
            if($v['record_type'] == 1)
            {//只发一次，一种货币
                $this->generateMessageRecord(0,9,$v['user_id'],[$v['user_id']]);
            }

        }

    }


    /**
     * 生成短信记录
     * @param $mobile 手机
     * @param $type 短信模板类型
     * @param array $user_id 用户ID
     * @param array $data 数据
     */
    private function generateMessageRecord($mobile,$type,$user_id=[],$data=[])
    {
        $this->smsData[] = ['mobile'=>$mobile,'type'=>$type,'user_id'=>$user_id,'data'=>$data];
    }

    /**
     * 发送短信
     */
    private function sendMsg()
    {
        if($this->smsData)
        {
            foreach ($this->smsData as $v)
            {
                SendMsg::dispatch($v['mobile'],$v['type'],$v['data'],$v['user_id']);
            }

        }
    }

    /**
     * 获取错误信息
     * @return mixed
     */
    public function getErrorMsg()
    {
        return $this->errorMsg;
    }

    /**
     * 更新所有创客推直接推荐用户数
     */
    public function updateRecommendedNumber()
    {
        $user = CisUserRepository::getInstance();
        $user_list = $user->getPerformanceUser();//查询所有可发工资的用户
        foreach ($user_list as $v)
        {
            if($v['x'] + $v['y'] > 2000)
            {
                $check = $user->findRecommendedNumber($v['id']);
                if($check)
                {
                    $set = [];
                    $set['user_renew'] = 1;
                    if(!$v['f'])
                    {
                        $set['repeated_consumption_date'] = date("Y-m-d",strtotime("+29 day"));
                    }
                    $user->updateUser($set,$v['id']);
                }
                else
                {
                    $user->updateUser(['user_renew'=>2],$v['id']);
                }

            }
        }
    }
}